package com.hyacinth.lotterysystem.service.impl;

import com.hyacinth.lotterysystem.common.errocde.ServiceErrorCodeConstants;
import com.hyacinth.lotterysystem.common.exception.ServiceException;
import com.hyacinth.lotterysystem.dto.req.CreatePrizeReq;
import com.hyacinth.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class PictureServiceImpl implements PictureService {
    @Value("${pic.local-path}")
    private String localPath;
    @Override
    public String savePicture(MultipartFile multipartFile){
        File dir = new File(localPath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        String fileName = multipartFile.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;

        try{
            multipartFile.transferTo(new File(localPath +"/"+fileName));
        }catch (IOException e){
            throw new ServiceException(ServiceErrorCodeConstants.PICTURE_UPLOAD_ERROR);
        }
        return fileName;
    }
}
